package com.demo.controller;

import com.demo.dao.Course;
import com.demo.dao.Gpa;
import com.demo.dao.Score;
import com.demo.service.CourseService;
import com.demo.service.GpaService;
import com.demo.service.ScoreService;
import com.demo.util.CalcuUtils;
import com.demo.util.DataParse;
import com.demo.util.POIUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@Api
public class FileController {


    @Autowired
    CourseService courseService;
    @Autowired
    ScoreService scoreService;
    @Autowired
    GpaService gpaService;

    @ApiOperation("上传文件")
    @PostMapping("/look")
    public void look(@RequestParam("excelFile") MultipartFile excelFile){
        try {
            List<DataParse> list = POIUtils.readExcel(excelFile);
            for (DataParse i: list
                 ) {

                String sid = i.getSid();
                int rank = i.getRank();
                double credit = i.getCredit();
                //首先写入gpa绩点表，包含sid，term，gpa，rank，其中gpa其实在数据中是credit
                Set<String> coursesname = i.getCourseAndMark().keySet();
                List<Integer> coursesCid = new ArrayList<>();
                for (String j: coursesname
                     ) {
                    coursesCid.add(courseService.getCidByName(j));
                }
                Course course = courseService.findCourseByCid(coursesCid.get(0));    //获得其中一门课的cid以得到学期
                String term = course.getTerm();
                Gpa gpa = new Gpa(sid,term,credit,rank);
                gpaService.insertCredit(gpa);
                //其次写入成绩表，sid,term,cid,mark,credit(需要计算)
                for (int cid: coursesCid
                     ) {
                    Score score = new Score();
                    score.setCid(cid);
                    score.setSid(sid);
                    int mark = i.getCourseAndMark().get(courseService.findNameById(cid));
                    score.setMark(mark);
                    score.setId(1);
                    score.setTerm(course.getTerm());
                    score.setCredit(CalcuUtils.calcuCredit(mark,courseService.findCourseByCid(cid).getCredit()));
                    scoreService.insertScore(score);
                }

            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
